﻿using AutoMapper;
using Domain.User;
using Infratructure.Interface;
using MD5Hash;
using MediatR;
using MES.Server.API.Application.Command.Account;
using ReturnValue;

namespace MES.Server.API.Application.Handler.Account
{
    public class AccountUpdateHandler:IRequestHandler<AccountUpdateCommand,ApiResult<int>>
    {
        private readonly IRepository<AccountModel> accountway;
        private readonly IRepository<AccountRoleModel> accountroleway;
        private readonly IRepository<RoleModel> roleway;
        private readonly ILogger<LoginHandler> log;
        private readonly IMapper mapper;
        private readonly IConfiguration configuration;

        public AccountUpdateHandler(IRepository<AccountModel> accountway, IRepository<AccountRoleModel>
            accountroleway, IRepository<RoleModel> roleway, ILogger<LoginHandler> log, IMapper mapper, IConfiguration configuration)
        {
            this.accountway = accountway;
            this.accountroleway = accountroleway;
            this.roleway = roleway;
            this.log = log;
            this.mapper = mapper;
            this.configuration = configuration;
        }
        /// <summary>
        /// 账号信息修改
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(AccountUpdateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var Count = accountway.GetAll().FirstOrDefault(x => x.AccountName == request.AccountName);
           
            if (Count != null)  //账号查重
            {
                res.Message = $"{DateTime.Now}:已有{request.AccountName},请重新编辑";
                res.Code = StatusCode.Fail;
                return res;  //返回
            }
            
            var value = mapper.Map<AccountModel>(request);
            value.AccountPwd = request.AccountPwd.GetMD5();  //密码
            var result = await accountway.UpdateAsync(value);
            if (result > 0)
            {
                log.LogInformation($"账号:{value.AccountName},信息修改成功");
                res.Message = $"账号:{value.AccountName},信息修改成功";
                res.Code = StatusCode.Success;
                res.Data = result;
            }
            else
            {
                res.Message = $"账号{value.AccountName}信息修改失败";
                res.Code = StatusCode.Fail;
            }
            return res;

        }
    }
}
